package com.it.gw.modules.water.activity.irr

import android.content.Intent
import android.util.Log
import android.widget.Toast
import androidx.activity.viewModels
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.it.common.bean.MapDataBean
import com.it.common.utils.GsonUtils
import com.it.common.utils.isNotEmpty
import com.it.data.network.req.IrrRecordDto
import com.it.gw.R
import com.it.gw.base.BaseActivity
import com.it.gw.databinding.ActivityIrrItemDetailBinding
import com.it.gw.dialog.ProgressDialog
import com.it.gw.manager.DictionariesManager
import com.it.gw.manager.DictionariesManager.CR_OVER_TYPE
import com.it.gw.manager.DictionariesManager.ENG_SCAL_1
import com.it.gw.manager.DictionariesManager.MAJ_WASO_TYPE
import com.it.gw.manager.DictionariesManager.SUP_WASO_TYPE
import com.it.gw.modules.map.activity.MapActivity
import com.it.gw.modules.water.viewmodel.WaterViewModel

//机井详情
class IrrItemDetailActivity : BaseActivity<ActivityIrrItemDetailBinding>() {
    private val waterViewModel by viewModels<WaterViewModel>()

    companion object {
        const val TAG = "DouQuItemDetailActivity"
    }


    override fun initObserver() {
        waterViewModel.irrRecordDtoDetailLiveData.observe(this) {
            ProgressDialog.hide()
            Log.d(TAG, "irrRecordDtoDetailLiveData: ${it}")
            if (it.result && it.data.isNotEmpty()) {
                setDetailView(it.data!!)
            }

        }
        waterViewModel.insertLiveData.observe(this) {
            ProgressDialog.hide()
            if (it.result) {
                Toast.makeText(this, "操作成功", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "${it.msg}", Toast.LENGTH_SHORT).show()
            }

        }

    }

    private fun setDetailView(data: IrrRecordDto) {
        binding.lttd.setText(data.lttd) // 纬度
        binding.irrCode.setText(data.irrCode) // 灌区代码
        binding.irrName.setText(data.irrName) // 灌区名称
        //binding.crOverType.setText(data.crOverType) // 跨界类型 （0 未知 1 跨国并跨省 2 跨国 3 跨省 4 跨地 5 跨县 6 县界内）

        //跨界类型
        binding.crOverType.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(CR_OVER_TYPE),
                code = data.crOverType
            )
        )


        binding.irrRang.setText(data.irrRang) // 灌区范围

        //binding.majWasoType.setText(data.majWasoType) // 主要水源工程类型 （1 水库 2 塘坝 3 河湖引水闸（坝、堰） 4 河湖泵站 5 机电井 6 混合 9 其他）
        //主要水源工程类型
        binding.majWasoType.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(MAJ_WASO_TYPE),
                code = data.majWasoType
            )
        )


        // binding.supWasoType.setText(data.supWasoType) // 补充水源工程类型

        binding.supWasoType.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(SUP_WASO_TYPE),
                code = data.supWasoType
            )
        )


//        binding.engScal.setText(data.engScal) // 工程规模（1 大（1）型 2 大（2）型 3 中型 4 小（1）型 5 小（2）型 9 其他）

        //工程规模
        binding.engScal.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(ENG_SCAL_1),
                code = data.engScal
            )
        )


        binding.desIrrArea.setText(data.desIrrArea) // 设计灌区面积
        binding.effIrrArea.setText(data.effIrrArea) // 有效灌区面积
        binding.adName.setText(data.adName) // 行政区划范围
        binding.lgtd.setText(data.lgtd) // 经度
        binding.note.setText(data.note) // 更新备注


    }


    override fun initListener() {

        binding.lgtd.setOnClickListener {
            startLocation()
        }
        binding.lttd.setOnClickListener {
            startLocation()
        }

        binding.btnSave.setOnClickListener {
            insertDouQRecord()

        }
        binding.crOverType.setOnClickListener {
            DictionariesManager.dictionariesMap.get(CR_OVER_TYPE)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.crOverType.text =
                            DictionariesManager.dictionariesMap.get(CR_OVER_TYPE)!![index].ITEMNAME

                    })
            }
        }

        binding.majWasoType.setOnClickListener {
            DictionariesManager.dictionariesMap.get(MAJ_WASO_TYPE)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.majWasoType.text =
                            DictionariesManager.dictionariesMap.get(MAJ_WASO_TYPE)!![index].ITEMNAME

                    })
            }
        }
        binding.supWasoType.setOnClickListener {
            DictionariesManager.dictionariesMap.get(SUP_WASO_TYPE)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.supWasoType.text =
                            DictionariesManager.dictionariesMap.get(SUP_WASO_TYPE)!![index].ITEMNAME

                    })
            }
        }
        binding.engScal.setOnClickListener {
            DictionariesManager.dictionariesMap.get(ENG_SCAL_1)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.engScal.text =
                            DictionariesManager.dictionariesMap.get(ENG_SCAL_1)!![index].ITEMNAME

                    })
            }
        }
    }

    private fun insertDouQRecord() {
        ProgressDialog.show(this)
        val dto = IrrRecordDto(
            lgtd = binding.lgtd.text.toString(), // 泵站经度
            irrCode = binding.irrCode.text.toString(), // 灌区代码
            irrName = binding.irrName.text.toString(), // 灌区名称
            // crOverType = binding.crOverType.text.toString(), // 跨界类型 （0 未知 1 跨国并跨省 2 跨国 3 跨省 4 跨地 5 跨县 6 县界内）
            crOverType = DictionariesManager.findCodeByName(
                list = DictionariesManager.dictionariesMap.get(CR_OVER_TYPE),
                name = binding.crOverType.text.toString()
            ),


            irrRang = binding.irrRang.text.toString(), // 灌区范围
            //majWasoType = binding.majWasoType.text.toString(), // 主要水源工程类型 （1 水库 2 塘坝 3 河湖引水闸（坝、堰） 4 河湖泵站 5 机电井 6 混合 9 其他）
            majWasoType = DictionariesManager.findCodeByName(
                list = DictionariesManager.dictionariesMap.get(MAJ_WASO_TYPE),
                name = binding.majWasoType.text.toString()
            ),


            //supWasoType = binding.supWasoType.text.toString(), // 补充水源工程类型

            supWasoType = DictionariesManager.findCodeByName(
                list = DictionariesManager.dictionariesMap.get(SUP_WASO_TYPE),
                name = binding.supWasoType.text.toString()
            ),


            //  engScal = binding.engScal.text.toString(), // 工程规模（1 大（1）型 2 大（2）型 3 中型 4 小（1）型 5 小（2）型 9 其他）

            engScal = DictionariesManager.findCodeByName(
                list = DictionariesManager.dictionariesMap.get(ENG_SCAL_1),
                name = binding.engScal.text.toString()
            ),
            desIrrArea = binding.desIrrArea.text.toString(), // 设计灌区面积
            effIrrArea = binding.effIrrArea.text.toString(), // 有效灌区面积
            adName = binding.adName.text.toString(), // 行政区划范围
            lttd = binding.lttd.text.toString(), // 维度
            note = binding.note.text.toString() // 更新备注
        )
        waterViewModel.insertIrrRecord(dto)

    }

    override fun initData() {
        ProgressDialog.show(this)
        getData()
    }

    private fun getData() {
        waterViewModel.getIrrBasic(intent.getStringExtra("id")!!)

    }


    var title = ""
    override fun initView() {
        DictionariesManager.getGuanQuDictionaries()
        title = "${intent.getStringExtra("title")}"
        setTitle(
            title = title,
            isBack = true,
            tvRightRes1 = R.string.str_location,
            tvRight1Action = {
                val intent = Intent(this, MapActivity::class.java)
                intent.putExtra("title", title)
                val mapList = mutableListOf(
                    MapDataBean(
                        name = title,
                        lgtd = binding.lgtd.text.toString(),
                        lttd = binding.lttd.text.toString(),
                    )
                )
                intent.putExtra(MapActivity.MAP_DATA, GsonUtils.objToJsonStr(mapList))
                startActivity(intent)
            }

        )

    }

    override fun setContentView() {
        binding = ActivityIrrItemDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }

    //声明AMapLocationClientOption对象
    private var mLocationOption: AMapLocationClientOption? = null

    //声明AMapLocationClient类对象
    private var mLocationClient: AMapLocationClient? = null
    private fun startLocation() {
        Log.d(TAG, "startLocation: ===========")
        mLocationClient = AMapLocationClient(applicationContext)
        mLocationClient?.setLocationListener(object : AMapLocationListener {
            override fun onLocationChanged(p0: AMapLocation?) {
                val longitude = "${p0?.longitude}"
                val latitude = "${p0?.latitude}"
                Log.d(TAG, "onLocationChanged: ${longitude} ${latitude}")
                binding.lttd.setText(latitude)
                binding.lgtd.setText(longitude)

            }

        })

        mLocationOption = AMapLocationClientOption()
        val option = AMapLocationClientOption()
        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn)
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        option.setOnceLocationLatest(true);

        if (null != mLocationClient) {
            mLocationClient?.setLocationOption(option)
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient?.stopLocation()
            mLocationClient?.startLocation()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mLocationClient?.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
    }


}